from tools.const import UserAgent

import requests
import random


def get_header(dic={}):
    user_agent = random.choice(UserAgent)
    header = {
        'User-Agent': user_agent
    }
    for k in dic:
        header[k] = dic[k]
    return header


def hua_ban(kw, page, per_page=24, sort='all'):
    url_ = 'https://api.huaban.com/search'
    headers_ = get_header()
    params_ = {
        'q': kw,
        'sort': sort,
        'per_page': per_page,
        'page': page,
        'hide_other_count': 1
    }
    resp = requests.get(url=url_, headers=headers_, params=params_)
    data = resp.json()
    pic_url = 'https://gd-hbimg.huaban.com/'
    # print(f'搜索网站：花瓣， 搜索内容：{kw}', '爬取内容如下：')
    # print(result['facets']['categories'])
    result = {'img': [], 'kw': kw, 'page': page}
    for i in data['pins']:
        file = {
            'type': i['file']['type'],
            'height': i['file']['height'],
            'width': i['file']['width'],
            'url': pic_url + i['file']['key']
        }
        result['img'].append(file)
        # i['file']['url'] = pic_url + i['file']['key']
        # i['file'].pop('key')
        # print(i['file'])
    return result


def hua_ban_kw(search):
    url_ = 'https://api.huaban.com/search/hint'
    headers_ = get_header()
    params_ = {
        'limit': 10,
        'q': search
    }
    resp = requests.get(url=url_, headers=headers_, params=params_)
    data = resp.json()
    print(search)
    return data